<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模板名称" prop="templateName">
        <el-input
          v-model="queryParams.templateName"
          placeholder="请输入模板名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="镜像名称" prop="imageName">
        <el-input
          v-model="queryParams.imageName"
          placeholder="请输入镜像名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="系统模板" prop="isSystem">
        <el-select v-model="queryParams.isSystem" placeholder="请选择是否系统模板" clearable>
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['datasync:server:manage']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['datasync:server:manage']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['datasync:server:manage']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['datasync:server:manage']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模板ID" align="center" prop="templateId" />
      <el-table-column label="模板名称" align="center" prop="templateName" :show-overflow-tooltip="true" />
      <el-table-column label="模板描述" align="center" prop="templateDescription" :show-overflow-tooltip="true" />
      <el-table-column label="镜像名称" align="center" prop="imageName" :show-overflow-tooltip="true" />
      <el-table-column label="镜像标签" align="center" prop="imageTag" />
      <el-table-column label="支持Compose" align="center" prop="useCompose">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.useCompose"/>
        </template>
      </el-table-column>
      <el-table-column label="是否系统模板" align="center" prop="isSystem">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isSystem"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['datasync:server:manage']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['datasync:server:manage']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            @click="handleDeploy(scope.row)"
            v-hasPermi="['datasync:server:manage']"
          >部署容器</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改Docker容器模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="模板名称" prop="templateName">
              <el-input v-model="form.templateName" placeholder="请输入模板名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否系统模板" prop="isSystem">
              <el-radio-group v-model="form.isSystem">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="模板描述" prop="templateDescription">
          <el-input v-model="form.templateDescription" type="textarea" placeholder="请输入模板描述" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="镜像名称" prop="imageName">
              <el-input v-model="form.imageName" placeholder="请输入镜像名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="镜像标签" prop="imageTag">
              <el-input v-model="form.imageTag" placeholder="请输入镜像标签" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="是否使用Compose" prop="useCompose">
              <el-radio-group v-model="form.useCompose" @change="handleComposeChange">
                <el-radio style="margin-right: 20px;" label="0">否</el-radio>
                <el-radio label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <div v-if="form.useCompose === '1'">
          <el-row>
            <el-col :span="24">
              <el-form-item label="Compose配置" prop="composeConfig">
                <el-input 
                  v-model="form.composeConfig" 
                  type="textarea" 
                  :rows="15" 
                  placeholder="请输入Docker Compose配置，YAML格式">
                </el-input>
                <div class="compose-hint">
                  <el-alert
                    title="Docker Compose配置示例"
                    type="info"
                    :closable="false">
                    <pre>version: "3"

services:
  db:
    image: mysql:5.7
    volumes:
      - db_data:/var/lib/mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: wordpress
      MYSQL_DATABASE: wordpress
      
  app:
    image: wordpress:latest
    ports:
      - "8080:80"
    volumes:
      - wp_data:/var/www/html
    depends_on:
      - db
      
volumes:
  db_data:
  wp_data:</pre>
                  </el-alert>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        
        <template v-if="form.useCompose === '0'">
          <el-form-item label="端口映射" prop="portMappings">
            <el-input v-model="form.portMappings" placeholder="格式: 宿主机端口:容器端口,分隔。例如: 6379:6379,8080:80" />
          </el-form-item>
          <el-form-item label="卷映射" prop="volumeMappings">
            <el-input v-model="form.volumeMappings" placeholder="格式: 宿主机路径:容器路径,分隔。例如: /data/redis:/data" />
          </el-form-item>
          <el-form-item label="环境变量" prop="environmentVars">
            <el-input v-model="form.environmentVars" placeholder="格式: 变量名=变量值,分隔。例如: MYSQL_ROOT_PASSWORD=123456" />
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="网络模式" prop="networkMode">
                <el-select v-model="form.networkMode" placeholder="请选择网络模式">
                  <el-option label="bridge" value="bridge" />
                  <el-option label="host" value="host" />
                  <el-option label="none" value="none" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="重启策略" prop="restartPolicy">
                <el-select v-model="form.restartPolicy" placeholder="请选择重启策略">
                  <el-option label="no" value="no" />
                  <el-option label="always" value="always" />
                  <el-option label="unless-stopped" value="unless-stopped" />
                  <el-option label="on-failure" value="on-failure" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="启动命令" prop="command">
            <el-input v-model="form.command" placeholder="可选，容器启动时执行的命令" />
          </el-form-item>
        </template>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    
    <!-- 部署容器对话框 -->
    <el-dialog :title="'部署 ' + deployForm.templateName + ' 容器'" :visible.sync="deployOpen" width="700px" append-to-body>
      <el-form ref="deployForm" :model="deployForm" :rules="deployRules" label-width="120px">
        <el-form-item label="选择服务器" prop="serverId">
          <el-select v-model="deployForm.serverId" filterable placeholder="请选择服务器" style="width: 100%">
            <el-option
              v-for="item in serverOptions"
              :key="item.serverId"
              :label="item.serverName"
              :value="item.serverId">
            </el-option>
          </el-select>
        </el-form-item>

        <!-- Compose模式 -->
        <template v-if="deployForm.useCompose === '1'">
          <el-form-item label="部署名称" prop="containerName">
            <el-input v-model="deployForm.containerName" placeholder="请输入部署名称，不填则自动生成" />
          </el-form-item>
          <el-form-item label="Compose配置" prop="composeConfig">
            <el-input v-model="deployForm.composeConfig" type="textarea" :rows="10" readonly />
            <div style="margin-top: 5px;">
              <el-alert
                title="使用Docker Compose模式部署，将使用模板中的Compose配置文件。"
                type="info"
                :closable="false">
              </el-alert>
            </div>
          </el-form-item>
        </template>

        <!-- 普通容器模式 -->
        <template v-else>
          <el-form-item label="容器名称" prop="containerName">
            <el-input v-model="deployForm.containerName" placeholder="请输入容器名称，不填则自动生成" />
          </el-form-item>
          
          <el-form-item label="端口映射">
            <div v-if="deployForm.templatePortMappings && deployForm.templatePortMappings.length > 0">
              <div v-for="(port, index) in deployForm.templatePortMappings" :key="index" style="margin-bottom: 10px;">
                <el-checkbox v-model="port.enabled" style="margin-right: 10px;">
                  {{ port.containerPort }}端口
                </el-checkbox>
                <el-input-number 
                  v-model="port.hostPort" 
                  :disabled="!port.enabled"
                  :min="1" 
                  :max="65535" 
                  style="width: 120px;"
                  @change="updatePortMappings"
                ></el-input-number>
                <span style="margin-left: 10px;">{{ port.description || '' }}</span>
              </div>
            </div>
            <div v-else>
              <el-input v-model="deployForm.customParams.portMappings" placeholder="格式: 宿主机端口:容器端口,分隔。例如: 6379:6379,8080:80" />
            </div>
          </el-form-item>
          
          <el-collapse>
            <el-collapse-item title="其他自定义参数（可选）">
              <el-form-item label="卷映射">
                <el-input v-model="deployForm.customParams.volumeMappings" placeholder="格式: 宿主机路径:容器路径,分隔。例如: /data/redis:/data" />
              </el-form-item>
              <el-form-item label="环境变量">
                <el-input v-model="deployForm.customParams.environmentVars" placeholder="格式: 变量名=变量值,分隔。例如: MYSQL_ROOT_PASSWORD=123456" />
              </el-form-item>
            </el-collapse-item>
          </el-collapse>
        </template>

        <!-- 显示实时部署过程 -->
        <el-form-item label="显示部署过程">
          <el-switch v-model="showDeployProcess" active-text="显示" inactive-text="隐藏"></el-switch>
        </el-form-item>
      </el-form>

      <!-- 部署过程输出区域 -->
      <div v-if="showDeployProcess && deployStarted" class="deploy-process-container">
        <div class="process-header">
          <span>部署过程实时输出</span>
          <el-button type="text" size="mini" @click="clearDeployLogs">清空</el-button>
        </div>
        <div class="process-content" ref="processContent">
          <div v-for="(log, index) in deployLogs" :key="index" :class="['log-item', log.type]">
            <span class="log-time">{{ log.time }}</span>
            <span class="log-message">{{ log.message }}</span>
          </div>
          <div v-if="deployLoading" class="loading-indicator">
            <i class="el-icon-loading"></i> 正在部署中...
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDeployForm" :loading="deployLoading">部 署</el-button>
        <el-button @click="cancelDeploy">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDockerTemplate, getDockerTemplate, delDockerTemplate, addDockerTemplate, updateDockerTemplate, exportDockerTemplate, createContainerFromTemplate, getDeployLogs } from "@/api/system/dockerTemplate";
import { listServerOptions } from "@/api/datasync/server";

export default {
  name: "DockerTemplate",
  dicts: ['sys_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // Docker容器模板表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateName: null,
        imageName: null,
        isSystem: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        templateName: [
          { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        imageName: [
          { required: true, message: "镜像名称不能为空", trigger: "blur" }
        ],
        imageTag: [
          { required: true, message: "镜像标签不能为空", trigger: "blur" }
        ]
      },
      // 部署容器相关
      deployOpen: false,
      deployLoading: false,
      serverOptions: [],
      deployForm: {
        templateId: null,
        templateName: "",
        serverId: null,
        containerName: "",
        customParams: {
          portMappings: "",
          volumeMappings: "",
          environmentVars: ""
        },
        templatePortMappings: []
      },
      deployRules: {
        serverId: [
          { required: true, message: "请选择服务器", trigger: "change" }
        ]
      },
      
      // 部署过程相关
      showDeployProcess: true,
      deployStarted: false,
      deployLogs: [],
      deployLogTimer: null,
      deployProcessId: null
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询Docker容器模板列表 */
    getList() {
      this.loading = true;
      this.total = 0; // 初始化total为0，防止NaN警告
      listDockerTemplate(this.queryParams).then(response => {
        this.templateList = response.data || [];
        this.total = parseInt(response.total || 0);
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        this.total = 0;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        templateId: null,
        templateName: null,
        templateDescription: null,
        imageName: null,
        imageTag: 'latest',
        useCompose: '0',
        composeConfig: null,
        portMappings: null,
        volumeMappings: null,
        environmentVars: null,
        networkMode: 'bridge',
        restartPolicy: 'unless-stopped',
        command: null,
        isSystem: '0',
        remark: null
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.templateId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加Docker容器模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const templateId = row.templateId || this.ids[0]
      getDockerTemplate(templateId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改Docker容器模板";
      });
    },
    /** 表单提交 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          console.log('提交表单:', this.form);
          // 确保Compose模式下的某些字段为空
          if (this.form.useCompose === '1') {
            // 在Compose模式下，这些字段应为空或默认值
            this.form.portMappings = null;
            this.form.volumeMappings = null;
            this.form.environmentVars = null;
            // 保留networkMode和restartPolicy的默认值
          }
          
          if (this.form.templateId != null) {
            updateDockerTemplate(this.form).then(response => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addDockerTemplate(this.form).then(response => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const templateIds = row.templateId || this.ids;
      this.$modal.confirm('是否确认删除Docker容器模板编号为"' + templateIds + '"的数据项？').then(function() {
        return delDockerTemplate(templateIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$confirm('是否确认导出所有Docker容器模板数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          return exportDockerTemplate(this.queryParams);
        }).then(response => {
          this.download(response.msg);
        });
    },
    /** 部署容器 */
    handleDeploy(row) {
      this.deployForm = {
        serverId: null,
        templateId: row.templateId,
        templateName: row.templateName,
        containerName: '',
        useCompose: row.useCompose,
        composeConfig: row.composeConfig,
        customParams: {
          portMappings: '',
          volumeMappings: row.volumeMappings,
          environmentVars: row.environmentVars,
          networkMode: row.networkMode,
          restartPolicy: row.restartPolicy,
          command: row.command
        },
        templatePortMappings: []
      };
      
      // 如果不是使用Compose，则处理端口映射
      if (row.useCompose !== '1' && row.portMappings && row.portMappings.trim() !== '') {
        const portMappings = row.portMappings.split(',');
        this.deployForm.templatePortMappings = portMappings.map(mapping => {
          const [hostPort, containerPort] = mapping.split(':');
          return {
            hostPort: parseInt(hostPort),
            containerPort: parseInt(containerPort),
            description: `${containerPort}端口映射`,
            enabled: true
          };
        });
        this.updatePortMappings();
      }
      
      // 获取服务器列表
      listServerOptions().then(response => {
        this.serverOptions = response.data;
      });
      
      this.deployOpen = true;
    },
    // 取消部署
    cancelDeploy() {
      this.clearDeployLogTimer();
      this.deployOpen = false;
      this.deployStarted = false;
      this.deployLogs = [];
    },
    // 更新端口映射字符串
    updatePortMappings() {
      if (this.deployForm.templatePortMappings && this.deployForm.templatePortMappings.length > 0) {
        // 过滤出启用的端口映射，然后格式化为字符串
        const enabledMappings = this.deployForm.templatePortMappings
          .filter(mapping => mapping.enabled)
          .map(mapping => `${mapping.hostPort}:${mapping.containerPort}`);
        
        this.deployForm.customParams.portMappings = enabledMappings.join(',');
      }
    },
    // 提交部署表单
    submitDeployForm() {
      this.$refs['deployForm'].validate(valid => {
        if (valid) {
          this.deployLoading = true;
          this.deployStarted = true;
          this.deployLogs = [];
          this.addDeployLog('info', '开始部署容器...');
          
          // 构建请求参数
          const data = {
            containerName: this.deployForm.containerName || null
          };
          
          // 处理不同模式的参数
          if (this.deployForm.useCompose === '1') {
            // Compose模式
            data.useCompose = '1';
            data.composeConfig = this.deployForm.composeConfig;
          } else {
            // 普通容器模式
            data.useCompose = '0';
            
            // 过滤空的自定义参数
            const customParams = {};
            if (this.deployForm.customParams.portMappings) {
              customParams.portMappings = this.deployForm.customParams.portMappings;
            }
            if (this.deployForm.customParams.volumeMappings) {
              customParams.volumeMappings = this.deployForm.customParams.volumeMappings;
            }
            if (this.deployForm.customParams.environmentVars) {
              customParams.environmentVars = this.deployForm.customParams.environmentVars;
            }
            
            if (Object.keys(customParams).length > 0) {
              data.customParams = customParams;
            }
          }
          
          createContainerFromTemplate(this.deployForm.serverId, this.deployForm.templateId, data).then(response => {
            if (response.data.success) {
              // 如果有显示过程，则开始轮询部署日志
              if (this.showDeployProcess && response.data.showProcess) {
                this.deployProcessId = response.data.processId;
                this.addDeployLog('command', '执行部署命令: ' + (response.data.command || '正在准备...'));
                
                // 显示初始日志
                if (response.data.logs) {
                  this.addDeployLog('output', response.data.logs);
                }
                if (response.data.errors) {
                  this.addDeployLog('error', response.data.errors);
                }
                
                // 开始轮询日志
                this.startPollingDeployLogs();
              } else {
                this.deployLoading = false;
                this.$modal.msgSuccess('容器部署成功');
                this.deployOpen = false;
              }
            } else {
              this.deployLoading = false;
              this.addDeployLog('error', '部署失败: ' + response.data.message);
              this.$modal.msgError('容器部署失败: ' + response.data.message);
            }
          }).catch(error => {
            this.deployLoading = false;
            this.addDeployLog('error', '请求异常: ' + error.message);
          });
        }
      });
    },
    // 处理Compose模式选择变更
    handleComposeChange(val) {
      console.log('Compose模式选择变更:', val);
      if (val === '1') {
        // 切换到Compose模式，清空普通模式的配置
        this.form.portMappings = null;
        this.form.volumeMappings = null;
        this.form.environmentVars = null;
        // 保留默认网络模式和重启策略
        if (!this.form.composeConfig) {
          // 如果Compose配置为空，提供默认模板
          this.form.composeConfig = 'version: "3"\n\nservices:\n  app:\n    image: nginx:latest\n    ports:\n      - "8080:80"\n    volumes:\n      - ./data:/data\n\nvolumes:\n  data:';
        }
      } else {
        // 切换到普通模式，清空Compose配置
        this.form.composeConfig = null;
      }
    },
    /** 开始轮询部署日志 */
    startPollingDeployLogs() {
      // 这里可以实现轮询获取部署日志的逻辑
      // 例如每3秒请求一次部署日志API
      this.deployLogTimer = setInterval(() => {
        this.pollDeployLogs();
      }, 3000);
      
      // 模拟获取部署日志
      setTimeout(() => {
        this.addDeployLog('output', '正在拉取镜像...');
      }, 1000);
      
      setTimeout(() => {
        this.addDeployLog('output', 'Using default tag: latest');
        this.addDeployLog('output', 'latest: Pulling from library/nginx');
      }, 2000);
      
      setTimeout(() => {
        this.addDeployLog('output', 'Digest: sha256:86e53c4c16a6a276b204b0fd3a8143d86547c967dc8258b3d47c3a21bb78cc42');
        this.addDeployLog('output', 'Status: Image is up to date for nginx:latest');
        this.addDeployLog('output', 'docker.io/library/nginx:latest');
      }, 4000);
      
      setTimeout(() => {
        this.addDeployLog('output', '创建容器...');
      }, 6000);
      
      setTimeout(() => {
        this.addDeployLog('success', '容器部署成功！容器ID: 7f23ed3f2c');
        this.deployLoading = false;
        this.$modal.msgSuccess('容器部署成功');
        
        // 清除轮询
        this.clearDeployLogTimer();
      }, 8000);
    },
    
    /** 轮询部署日志 */
    pollDeployLogs() {
      // 调用API获取最新的部署日志
      getDeployLogs(this.deployForm.serverId, this.deployProcessId).then(response => {
        if (response.code === 200) {
          const data = response.data;
          
          // 添加新的日志
          if (data.logs && data.logs.length > 0) {
            const currentLogs = this.deployLogs.map(log => log.message);
            
            // 只添加新的日志条目
            data.logs.forEach(logMsg => {
              if (!currentLogs.includes(logMsg)) {
                // 根据日志内容判断类型
                let type = 'output';
                if (logMsg.includes('[步骤]')) {
                  type = 'info';
                } else if (logMsg.includes('[命令]')) {
                  type = 'command';
                } else if (logMsg.includes('[异常]') || logMsg.includes('[失败]')) {
                  type = 'error';
                } else if (logMsg.includes('[完成]') && logMsg.includes('成功')) {
                  type = 'success';
                }
                
                this.addDeployLog(type, logMsg);
              }
            });
          }
          
          // 如果部署已完成，停止轮询
          if (data.completed) {
            this.clearDeployLogTimer();
            this.deployLoading = false;
            
            if (data.success) {
              this.$modal.msgSuccess('容器部署成功');
              this.deployOpen = false;
            } else {
              this.$modal.msgError('容器部署失败，请查看日志了解详情');
            }
          }
        }
      }).catch(error => {
        console.error('获取部署日志失败:', error);
      });
    },
    
    /** 清除部署日志轮询定时器 */
    clearDeployLogTimer() {
      if (this.deployLogTimer) {
        clearInterval(this.deployLogTimer);
        this.deployLogTimer = null;
      }
    },
    
    /** 添加部署日志 */
    addDeployLog(type, message) {
      const now = new Date();
      const time = now.getHours().toString().padStart(2, '0') + ':' + 
                   now.getMinutes().toString().padStart(2, '0') + ':' + 
                   now.getSeconds().toString().padStart(2, '0');
      
      this.deployLogs.push({
        time,
        type,
        message
      });
      
      // 自动滚动到底部
      this.$nextTick(() => {
        if (this.$refs.processContent) {
          this.$refs.processContent.scrollTop = this.$refs.processContent.scrollHeight;
        }
      });
    },
    
    /** 清空部署日志 */
    clearDeployLogs() {
      this.deployLogs = [];
    }
  }
};
</script>

<style lang="scss" scoped>
.compose-hint {
  margin-top: 10px;
  max-height: 300px;
  overflow-y: auto;
  
  pre {
    background-color: #f5f5f5;
    padding: 10px;
    border-radius: 4px;
    font-family: 'Courier New', Courier, monospace;
    font-size: 12px;
    white-space: pre-wrap;
    word-break: break-all;
  }
}

.deploy-process-container {
  margin-top: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  
  .process-header {
    padding: 8px 15px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #dcdfe6;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .process-content {
    height: 300px;
    overflow-y: auto;
    padding: 10px 15px;
    background-color: #1e1e1e;
    color: #f0f0f0;
    font-family: Consolas, Monaco, 'Andale Mono', monospace;
    font-size: 12px;
    line-height: 1.5;
    
    .log-item {
      margin-bottom: 5px;
      white-space: pre-wrap;
      word-break: break-all;
      
      &.info {
        color: #7ec699;
      }
      
      &.command {
        color: #569cd6;
      }
      
      &.output {
        color: #f0f0f0;
      }
      
      &.error {
        color: #f56c6c;
      }
      
      &.success {
        color: #67c23a;
      }
      
      .log-time {
        color: #888;
        margin-right: 8px;
      }
    }
    
    .loading-indicator {
      margin-top: 10px;
      color: #409eff;
    }
  }
}
</style> 